/*
 * Copyright (C) 2013 Andreas Stuetz <andreas.stuetz@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bingkaimedia.merchantbeta.app;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bingkaimedia.merchantbeta.R;
import com.bingkaimedia.merchantbeta.libs.JSONfunctions;
import com.bingkaimedia.merchantbeta.libs.LazyAdapter;
import com.bingkaimedia.merchantbeta.libs.SessionManager;
import com.bingkaimedia.merchantbeta.libs_grid.CustomGridViewAdapter1;
import com.bingkaimedia.merchantbeta.libs_grid.CustomGridViewAdapter2;
import com.bingkaimedia.merchantbeta.libs_grid.Item;
import com.bingkaimedia.merchantbeta.libs_slidemenu.BaseActivity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;


@SuppressLint("NewApi")
public class Channel_My extends BaseActivity {
	
	
  
	ArrayList<Item> gridArray1 = new ArrayList<Item>();
	ArrayList<Item> gridArray2 = new ArrayList<Item>();
	CustomGridViewAdapter1 customGridAdapter1;
	CustomGridViewAdapter2 customGridAdapter2;
	 
	int current_page = 0;
	

	// XML node keys
	//static final String KEY_SONG = "song"; // parent node
	public static final String KEY_VOUCHER_ID = "voucher_id";
	public static final String KEY_VOUCHER_NAME = "voucher_name"; 
	public static final String KEY_VOUCHER_TOTAL = "voucher_total";
	public static final String KEY_VOUCHER_TERSEDIA = "voucher_tersedia";
	public static final String KEY_MERCHANT_NAME = "merchant_name";
	public static final String KEY_MERCHANT_CATEGORY = "merchant_category";
	public static final String KEY_MERCHANT_PHOTO = "merchant_photo";
	public static final String KEY_VOUCHER_DETAIL = "voucher_detail";
	public static final String KEY_VOUCHER_DESCRIPTION = "voucher_description";
	public static final String KEY_MERCHANT_ID = "merchant_id";
	

	public static final String KEY_MY_CHANNEL_ID = "my_channel_id";
	public static final String KEY_CHANNEL_ID = "channel_id";
	public static final String KEY_USERS_ID = "users_id";
	public static final String KEY_CHANNEL_NAME = "channel_name";
	public static final String KEY_CHANNEL_ADDRESS = "channel_address";
	public static final String KEY_CHANNEL_PHOTO = "channel_photo";
	public static final String KEY_CHANNEL_NOTE = "channel_note";
	
	 

	private String xml_voucher_id;
	private String xml_voucher_name;
	private String xml_voucher_total;
	private String xml_voucher_tersedia;
	private String xml_voucher_description;
	private String xml_voucher_detail;
	private String xml_merchant_id;
	private String xml_merchant_name;
	private String xml_merchant_category;
	private String xml_merchant_photo;
	

	private String xml_my_channel_id;
	private String xml_channel_id;
	private String xml_users_id;
	private String xml_channel_name;
	private String xml_channel_photo;
	private String xml_channel_note;
	private String xml_channel_address;
	

	private String xml_my_channel_id2;
	private String xml_channel_id2;
	private String xml_users_id2;
	private String xml_channel_name2;
	private String xml_channel_photo2;
	
	private static String session_userid;
	private static String session_username;
	private static String session_password;
	private static String session_email;
	private static String session_city;
	private static String session_checked;
     
	SessionManager session;
	
	private LazyAdapter adapter;
	ArrayList<HashMap<String, String>> menuItems;
	ProgressDialog pDialog1, pDialog2;
	HashMap<String, String> map = new HashMap<String, String>();
	
	ArrayList<HashMap<String, String>> diskonba_list = new ArrayList<HashMap<String, String>>();
	 
	private LinearLayout slidingPanel;
	private boolean isExpanded;
	private DisplayMetrics metrics;
	private RelativeLayout headerPanel;
	private int panelWidth;
	private int panelWidth1;
	private Button btnLoadMore;

	private ImageView menuViewButton,menuRightButton;

	FrameLayout.LayoutParams menuPanelParameters;
	FrameLayout.LayoutParams slidingPanelParameters;
	LinearLayout.LayoutParams headerPanelParameters;
	LinearLayout.LayoutParams listViewParameters;


	private int count;
	private String json;
	private String result;
	private JSONObject jsonobject;
	public String code;
	public String msg;
	
	public ListView lv;
	public GridView gridView1, gridView2;
	
	private SlidingMenu sm;
	 
	public Channel_My() {
		super(R.string.baru); 
	}


	@Override
	public void onBackPressed() { 
		Channel_My.this.finish();
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.channel_my);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
		
		fungsi_menu();
		
		session = new SessionManager(getApplicationContext());
	    
	    HashMap<String, String> user = session.getUserDetails();
	     
	     
	    // session
	    session_userid = user.get(SessionManager.id_users);
	    session_username = user.get(SessionManager.username);
	    session_password = user.get(SessionManager.password);
	    session_email = user.get(SessionManager.email);
	    session_city = user.get(SessionManager.city);
	    session_checked = user.get(SessionManager.checked);
		
	    
	    gridView1 = (GridView) findViewById(R.id.gridView1);		
	    new my_channel().execute();
	    
	     
	    
		gridView1.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String list_id = ((TextView) view.findViewById(R.id.item_id))
						.getText().toString();
				//System.out.println(list_id);
				
				Intent in = new Intent(getApplicationContext(),
						Channel_My_Detail.class);
				in.putExtra(KEY_CHANNEL_ID, list_id);
				startActivity(in);
				Channel_My.this.finish();
			}
		});
		
		  
	}
 

	public void fungsi_menu(){
		
		setSlidingActionBarEnabled(true);
		 
        sm = getSlidingMenu();
		 
		LinearLayout header_vertical_divider_1 = (LinearLayout) findViewById(R.id.header_vertical_divider_1);
		LinearLayout header_vertical_divider_2 = (LinearLayout) findViewById(R.id.header_vertical_divider_2);
		ImageView diskonion_iconmenu = (ImageView) findViewById(R.id.diskonion_iconmenu);
		ImageView diskonion_iconhome = (ImageView) findViewById(R.id.diskonion_iconhome);
		ImageView diskonion_iconsearch = (ImageView) findViewById(R.id.diskonion_iconsearch);
		ImageView diskonion_iconcategory = (ImageView) findViewById(R.id.diskonion_iconcategory);
		
		 
		
		diskonion_iconmenu.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				sm.showMenu(); 
			}
		}); 
		
		diskonion_iconhome.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				//sm.showSecondaryMenu();
 				Intent intent=new Intent(getApplicationContext(),Home.class);
 				startActivity(intent);
			}
		});
		
		diskonion_iconsearch.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				//sm.showSecondaryMenu();
 				Intent intent=new Intent(getApplicationContext(),Search.class);
 				startActivity(intent);
			}
		});
		
		diskonion_iconcategory.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				sm.showSecondaryMenu(); 
			}
		});
 		
	}
	
	 
	@SuppressLint("NewApi")
	private class my_channel extends AsyncTask<Void, Void, Void>  {

		private String json;
		private JSONObject jsonobject;
		public String code;
		public String msg;
		

		
		@Override
		protected void onPreExecute() {
			// Showing progress dialog before sending http request
			pDialog1 = new ProgressDialog(
					Channel_My.this);
			pDialog1.setMessage("Retrieve Data, Please wait...");
			pDialog1.setIndeterminate(true);
			pDialog1.setCancelable(true); 
			pDialog1.show();

			code="99";
			msg="Not connected to server";
			
		}

		protected Void doInBackground(Void... unused) {
			String result = null;
			InputStream is = null;
			StringBuilder sb=null; 

			Global.URL = Global.link_channel_my + session_userid ;
			//System.out.println(Global.URL); 
			
			try{ 
				json=JSONfunctions.getStringContent(Global.URL);
				jsonobject=new JSONObject(json); 
				code=jsonobject.getString("code");
				msg=jsonobject.getString("msg");
				 
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				System.out.println("catch code msg");
				System.out.println(e);
				pDialog1.dismiss();
				//Toast.makeText(getApplicationContext(), "Something wrong in your connection", Toast.LENGTH_LONG).show();
			
			}
			
			System.out.println("code "+code);
			if(code.equalsIgnoreCase("99")){
				try{ 
					System.out.println(Global.URL);
					//json=JSONfunctions.getStringContent2(Global.URL);
					System.out.println(json); 
					 
				}
				catch (Exception e) 
				{
					e.printStackTrace();
					System.out.println("catch 1");
					System.out.println(e);

					pDialog1.dismiss();
					//Toast.makeText(getApplicationContext(), "Something wrong in your connection (1)", Toast.LENGTH_LONG).show();
				
				}
			}
		  
			return null;
			
			 
		}
		
		
		protected void onPostExecute(Void unused) { 
			count = 0;  
			result = json;
		 
			if(code.equalsIgnoreCase("0")){
				
				Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
			}
			else{
				try{ 
			      	JSONArray jArray = new JSONArray(result);
			      	JSONObject json_data=null;
	
			      	//System.out.println("array length");
			      	//System.out.println(jArray.length());
			      	
			      	for(int i=0;i<jArray.length();i++){
						json_data = jArray.getJSONObject(i); 
						 
						
						xml_my_channel_id = json_data.getString(KEY_MY_CHANNEL_ID);
						xml_channel_id = json_data.getString(KEY_CHANNEL_ID);
						xml_users_id = json_data.getString(KEY_USERS_ID);
						xml_channel_name = json_data.getString(KEY_CHANNEL_NAME);
						xml_channel_photo = json_data.getString(KEY_CHANNEL_PHOTO);
						
						xml_channel_photo = Global.path + xml_channel_photo;
						 
						//System.out.println(xml_channel_photo);
						  
						   
						gridArray1.add(new Item(xml_channel_photo,xml_channel_name,xml_channel_id));
						  
			      		}
			      	
				}catch(JSONException e1){ 
					System.out.println("catch 2");
					System.out.println(e1);
					Toast.makeText(getBaseContext(), "Something wrong in your connection (2)", Toast.LENGTH_LONG).show();
				}catch (ParseException e1){ 
					System.out.println("catch 3");
					System.out.println(e1);
					Toast.makeText(getBaseContext(), "Something wrong in your connection (3)", Toast.LENGTH_LONG).show();	
				} 
			}
			
			customGridAdapter1 = new CustomGridViewAdapter1(Channel_My.this, R.layout.row_grid1, gridArray1);
			gridView1.setAdapter(customGridAdapter1);
			//System.out.println("selesai");
			pDialog1.dismiss();
		}
	}
 
  

}